package cn.thoughtworks.school.programCenter.repositories;

import cn.thoughtworks.school.programCenter.entities.UserProgram;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;

public interface UserProgramRepository extends JpaRepository<UserProgram, Long> {

    List<UserProgram> findByProgramId(Long programId);

    UserProgram findByProgramIdAndUserId(Long programId, Long userId);

    List<UserProgram> findByProgramIdAndUserIdIn(Long programId, List<Long> userIds);

    @Modifying
    @Transactional
    @Query("delete from UserProgram  where programId=?1 and userId=?2")
    void deleteByProgramIdAndStudentId(Long programId, Long studentId);

    @Query(value = "select * from userProgram up where userId = ?1 and programId in (select id from program where available =1 and isExpired=false)",nativeQuery = true)
    Page<UserProgram> findByUserIdAndProgramIdIsAvailableAndNotIsExpired(Long id, Pageable pageable);
    @Query(value = "select * from userProgram up where userId = ?1 and programId in (select id from program where available =1)",nativeQuery = true)
    List<UserProgram> findByUserIdAndProgramIdIsTrue(Long id);

    List<UserProgram> findByProgramIdIn(List<Long> programIds);

    @Query(value = "select * from userProgram up where userId = ?1 and programId in (select id from program where available =1 and isExpired=false)",nativeQuery = true)
    List<UserProgram> findByUserIdAndProgramIdIsAvailableAndNotIsExpired(Long id);

}
